#!/usr/bin/env python3
# ish-gps.py  —— 在 iSH 里实时打印当前经纬度
import time, os, sys

fd = None
while True:
    try:
        if fd is None:                     # 第一次打开 /dev/location
            fd = os.open('/dev/location', os.O_RDONLY | os.O_NONBLOCK)

        raw = os.read(fd, 1024).decode('ascii', errors='ignore').strip()
        if not raw.startswith('$GPGGA'):
            time.sleep(0.2)                # 不是 GGA 就稍等再读
            continue

        parts = raw.split(',')
        if len(parts) < 10:
            continue                       # 字段不够，丢弃

        lat_raw, lat_dir = parts[2], parts[3]
        lon_raw, lon_dir = parts[4], parts[5]

        # NMEA 纬度格式：ddmm.mmmm   经度：dddmm.mmmm
        lat = float(lat_raw[:2]) + float(lat_raw[2:]) / 60
        lon = float(lon_raw[:3]) + float(lon_raw[3:]) / 60
        if lat_dir == 'S':
            lat = -lat
        if lon_dir == 'W':
            lon = -lon

        # 清掉上一行，原地刷新
        sys.stdout.write('\r%.6f°, %.6f°   ' % (lat, lon))
        sys.stdout.flush()
        time.sleep(1)

    except KeyboardInterrupt:
        print('\nbye')
        break
    except Exception as e:
        # 设备还没就绪或权限问题
        sys.stdout.write('\rwaiting for location…   ')
        sys.stdout.flush()
        time.sleep(1)
